#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import time

from common.common import execute_cmd_list, execute_cmd
from common.const import CMDResult
from mysql import log
from mysql.src.common.constant import SystemServiceType, MySQLClusterType, MySQLStrConstant, MYSQL_SERVICE_LIST
from mysql.src.common.execute_cmd import is_port_in_use


def get_service_info(service_name, include_exited=True):
    try:
        ret, _, _ = execute_cmd_list([f"systemctl status {service_name}", "grep \"Active: active (running)\""],
                                     True)
        if ret == CMDResult.SUCCESS.value:
            log.info(f"Mysql systemctl {service_name} running.")
            return True, SystemServiceType.SYSTEMCTL, service_name
        if include_exited:
            ret, _, _ = execute_cmd_list([f"systemctl status {service_name}", "grep \"Active: active (exited)\""],
                                         True)
            if ret == CMDResult.SUCCESS.value:
                log.info(f"Mysql systemctl {service_name} running.")
                return True, SystemServiceType.SYSTEMCTL, service_name,
    except Exception as exception_str:
        log.info(f"get_mysql_service_info exception_str:{exception_str}")
    service_ret, success_out, error_out = execute_cmd(f"service {service_name} status")
    log.info(success_out)
    if service_ret != CMDResult.SUCCESS.value:
        log.error(f"Get service {service_name} status error. error out: {error_out}")
        return False, "", ""
    # 命令执行成功，根据回显的字符串，判断是否有这个服务，如果有这个服务则判断这个服务是否处于running状态
    if success_out.find("could not be found") != -1:
        log.error(f"Get service {service_name} status error.service is not be found. out: {success_out}")
        return False, "", ""
    if success_out.find("SUCCESS!") != -1 or success_out.find("running") != -1:
        log.info(f"Get service {service_name} status is running. out: {success_out}")
        return True, SystemServiceType.SERVICE, service_name
    if success_out.find("0/SUCCESS") != -1 and success_out.find("active (running)") != -1:
        log.info(f"Get service {service_name} status is running. out: {success_out}")
        return True, SystemServiceType.SERVICE, service_name
    return False, "", ""
